package com.wl.dzt.sys.core.dao.curd.mssql;

import com.wl.dzt.sys.core.dao.curd.CrudConvert;
import com.wl.dzt.sys.core.dao.curd.CrudConvertResult;
import com.wl.dzt.sys.core.dao.select.Select;
import com.wl.dzt.sys.core.dao.select.SelectMate;
import com.wl.dzt.sys.core.dao.select.SelectSqlBuilder;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;


/**
 * @author wl_code@163.com
 * @version 1.0
 * @date 2018/7/5/005
 * @description microsoft sql server转换
 */
@Component
public class CrudConvertForMssql implements CrudConvert {

    /**
     * mysql查询构建器
     */
    @Resource
    private SelectSqlBuilder selectSqlBuilderForMssql;

    /**
     * 根据mssql的语法特性转换查询语句
     *
     * @param select
     * @return
     */
    public CrudConvertResult selectConvert(Select select) {
        CrudConvertResult convertResult = new CrudConvertResult();
        SelectMate selectMate = selectSqlBuilderForMssql.assembleAll(select);
        convertResult.setArgs(selectMate.getArgs().toArray());
        convertResult.setSql(select.getLimit() > 0 ? (selectMate.toPageSqlNotOrder() + selectMate.getOrderSql()) : selectMate
                .toSql());
        return convertResult;
    }

    /**
     * 根据mssql的语法特性转换总数查询语句
     *
     * @param select
     * @return
     */
    public CrudConvertResult countConvert(Select select) {
        CrudConvertResult convertResult = new CrudConvertResult();
        SelectMate selectMate = selectSqlBuilderForMssql.assembleAll(select);
        convertResult.setSql(selectMate.toCountSql());
        convertResult.setArgs(selectMate.getArgs().toArray());
        return convertResult;
    }

    public void changeSelectSqlBuilderForMysql(SelectSqlBuilderForMssql selectSqlBuilderForMssql) {
        this.selectSqlBuilderForMssql = selectSqlBuilderForMssql;
    }

    /**
     * 获取分页sql模板
     * 其中参数位置用%s表示
     *
     * @return
     */
    public String getPageTemplate() {
        return (" SELECT temp.* FROM  ( %s ) temp  WHERE tempPageIndexRowNumber BETWEEN  %s AND %s ");
    }

}
